/**
 * 用户套餐余额
 */
import { gqcPermissionCheck } from '@kuiper/auth';
import set from 'lodash/set';
import schemas from './schemas';

export default server => {
	const Balance = server.methods.registerMongoModel({
		name: 'Balance',
		schema: schemas.balance,
	});
	server.methods.registerGraphQLSchema({
		name: 'Balance',
		model: Balance,
		queryFields: {
			One: 'findOne',
		},
		mutationFields: {},
		onPreAddFields(tc) {
			const {
				app: {
					schemaComposer,
					graphqlResolvers,
					schema: { Package },
				},
			} = server;

			tc.addRelation('plan', {
				resolver: () => Package.mongooseResolvers.dataLoader({ lean: true }),
				prepareArgs: {
					_id: source => source.planId,
				},
				projection: { planId: 1 },
			});

			// 请求时计算value值
			const valueResolver = () =>
				schemaComposer.createResolver({
					name: 'BalanceValue',
					type: 'Int',
					args: {
						total: 'Int!',
						used: 'Int!',
					},
					resolve: ({ args: { total, used } }) => total - used,
				});
			Object.entries(tc.getFieldTC('balance')._gqcFields).forEach(
				([_field, { type }]) => {
					type.addRelation('value', {
						prepareArgs: {
							total: source => source.total,
							used: source => source.used,
						},
						projection: {
							total: true,
							used: true,
						},
						resolver: valueResolver,
					});
				}
			);

			graphqlResolvers.Query.BalanceOne = graphqlResolvers.Query.BalanceOne.withMiddlewares(
				[
					gqcPermissionCheck({
						required: 'billing\x01getBalance',
						selfOnlyArgsBuilder(
							_source,
							args,
							{
								request: {
									auth: {
										credentials: { uid },
									},
								},
							}
						) {
							set(args, ['filter', 'uid'], uid);
						},
					}),
				]
			);
		},
	});
};
